﻿using D.B.Data.API.Applications.Command.MenusCommand;
using D.B.Data.Domain;
using D.B.Data.ErrorCode;
using D.B.Data.Infrastructuse;
using MediatR;
using System.Threading.Tasks;

namespace D.B.Data.API.Applications.CommandHandler.MenusCommandHandler
{
    public class DelMenusCommandHandler : IRequestHandler<DelMenusCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MenusModel> baseRepository;
        

        public DelMenusCommandHandler(IBaseRepository<MenusModel> baseRepository)
        {
            this.baseRepository = baseRepository;
        }

        public async Task<APIResult<int>> Handle(DelMenusCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var res = baseRepository.GetAll().ToList();
            var count =await Del(request.Id, res);
            


            if (count > 0)
            {
                result.Code=EnumCode.Ok;
                result.Msg = "删除成功";
            }
            else
            {
                result.Code = EnumCode.File;
                result.Msg = "删除失败";
            }
            result.Data = count;
            return await Task.FromResult(result);
        }

        public async Task<int> Del(long Id,List<MenusModel> ids)
        {
            int count = 0;
            var res1 = ids.FirstOrDefault(s => s.Id == Id);
            if (res1!=null&&!res1.IsDel)
            {
                res1.IsDel = true;
                baseRepository.Update(res1);
                count++;

                var res = ids.Where(s => s.Pid == Id &&! s.IsDel).ToList();
                //有子集
                foreach (var item in res)
                {
                    count += await Del(item.Id, ids);
                }

            }
            return count;


        }
    }
}
